<?php

declare(strict_types=1);

/**
 * @Author:     Frank
 * @contact     frank_hhm@163.com
 * @Date:       2023-02-08 21:51:48
 * @Last Modified time: 2023-02-16 16:14:38
 */
namespace app\common\services\store;

use frank\base\BaseService;
use frank\exception\CommonException;
use app\common\dao\store\OrderDeliveryDao;
use app\common\services\store\OrderService;

/**
 * 订单发货单
 * Class OrderDeliveryService
 */
class OrderDeliveryService extends BaseService
{
    /**
     * OrderDeliveryService constructor.
     * @param UserAddressDao $dao
     */
    public function __construct(OrderDeliveryDao $dao)
    {
        $this->dao = $dao;
    }

    public function getDeliveryDetail($filter)
    {
        $detail = $this->dao->search($filter)->find();
        if (!$detail) {
            throw new CommonException('发货单不存在');
        }
        return $detail->toArray();
    }

    /**
     * 获取发货单列表
     */
    public function getDeliverySelect(array $where = [])
    {
        $list = $this->dao->getDeliverySelect($where);
        return $list;
    }

    /**
     * 将订单商品添加入发货单
     */
    public function createDelivery($goodsList,$deliveryType){
        $list = [];
        foreach ($goodsList as $key => $item) {
            $list[] = [
                'order_goods_id'=>$item['id'],
                'goods_id'=>$item['goods_id'],
                'order_id'=>$item['order_id'],
                'user_id'=>$item['user_id'],
                'delivery_type'=>$deliveryType,
            ];
        }
        return $this->dao->saveAll($list);
    }

    /**
     * 订单商品标记发货
     */
    public function orderGoodsDelivery($orderId,$data){
        if (empty($data['order_goods_id'])) {
            $this->error = '没有需要核销的商品';
            return false;
        }
        $order = OrderService::instance()->getOrderDetail([
            'id'=>$orderId
        ]);
         // 判断订单是否有效
        if ($order['pay_status']['value'] != 1) {
            $this->error = '该订单未支付';
            return false;
        }

        if(
            $order['delivery_type']['value'] == 'slef_mention' 
            && $order['extract_code'] !== $data['extract_code']
        ) {
            $this->error = '取货码不正确';
            return false;
        }

        $deliveryType = $order['delivery_type']['value'];

        $status = $this->transaction(function () use ($data,$deliveryType) {

            $saveData = [
                'delivery_status'=>1,
                'delivery_time'=>time()
            ];
            
            if($deliveryType == 'express'){
                $saveData['delivery_no'] = $data['delivery_no'];
                $saveData['delivery_mode'] = $data['delivery_mode'];
                $saveData['express_company_id'] = $data['express_company_id'] ?? 0;
            }
            // 更新订单状态
            return $this->dao->search(['order_goods_id'=>$data['order_goods_id']])->save($saveData);
            // 新增订单核销记录
        });

        // 如果不存在未发货，订单则完成发货
        if($this->checkComplete($orderId)){
            OrderService::instance()->deliveryComplete($orderId,$deliveryType);
        }
        return $status;
    }

    public function checkComplete($orderId){
        $count = $this->dao->search([
            'order_id'=>$orderId,
            'delivery_status'=>0
        ])->count();
        if($count > 0){
            return false;
        }
        return true;
    }
}